package com.trainoo.payment.mock.service;

import com.trainoo.payment.mock.cache.LocalCache;
import com.trainoo.payment.mock.cache.PayerIdCache;
import com.trainoo.payment.mock.util.DateUtil;
import com.trainoo.payment.mock.util.HttpUtil;
import com.trainoo.payment.mock.util.PayerGenUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * <p> add description here </p>
 *
 * @author tao.zhou
 * @version 1.0
 * @date 2021/12/3 17:32:00
 */

public class PayNotifyThread implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(PayNotifyThread.class);

    private String url;
    private String transId;
    private String origOrderNo;
    private Long sleepTime;

    PayNotifyThread(String url, String transId, String origOrderNo, Long sleepTime){
        this.url = url;
        this.transId = transId;
        this.origOrderNo = origOrderNo;
        this.sleepTime = sleepTime;
    }

    @Override
    public void run() {
        // 不为空则sleep延时
        if (null != this.sleepTime && this.sleepTime != 0L) {
            try {
                Thread.sleep(this.sleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        NameValuePair origOrderNo = new BasicNameValuePair("origOrderNo", this.origOrderNo);
        NameValuePair transId = new BasicNameValuePair("transId", this.transId);
        NameValuePair payTime = new BasicNameValuePair("payTime", DateUtil.getYMDStr());
        String key = String.format(LocalCache.PAYER_INFO, this.origOrderNo);
        PayerIdCache payerIdCache;
        if (LocalCache.exist(key)) {
            payerIdCache =  ((PayerIdCache) LocalCache.get(key));
        }else {
            payerIdCache = PayerGenUtil.genPayerIdAndFourthTransNo();
            LocalCache.set(key,payerIdCache);
        }
        NameValuePair fourthTransNo = new BasicNameValuePair("fourthTransNo", payerIdCache.getFourthTransNo());
        NameValuePair payerId = new BasicNameValuePair("payerId", payerIdCache.getPayerId());
        List<NameValuePair> pairList = new ArrayList<>();
        pairList.add(origOrderNo);
        pairList.add(transId);
        pairList.add(payTime);
        pairList.add(fourthTransNo);
        pairList.add(payerId);
        try {
            String result = HttpUtil.post(url, pairList);
            logger.info("支付回调成功！ack={}", result);
        } catch (Exception e) {
            logger.error("支付回调异常！！{}", pairList);
        }
    }
}
